package com.example.oss.storage.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.example.oss.storage.IStorage;

import java.io.InputStream;
import java.util.Date;

public class AliyunStorage implements IStorage {

    private final OSS ossClient;


    public AliyunStorage(OSS ossClient) {
        this.ossClient = ossClient;
    }

    //上传文件
    @Override
    public void putObject(String bucketName, String objectName, InputStream inputStream, String contentType) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(contentType);
        this.ossClient.putObject(bucketName, objectName, inputStream, objectMetadata);
    }


    @Override
    public InputStream getObject(String buckName, String objectName) {
        return ossClient.getObject(buckName, objectName).getObjectContent();
    }

    @Override
    public String getPublicObjectUrl(String buckName, String objectName) {
        String signedUrl = getSignedObjectUrl(buckName, objectName);
        return signedUrl.split("\\?")[0];  //删除？后多余属性
    }

    @Override
    public String getSignedObjectUrl(String buckName, String objectName) {
        Date date = new Date(System.currentTimeMillis() + 3600*1000);
        return ossClient.generatePresignedUrl(buckName, objectName, date).toString();
    }
}
